from hilo_module import *

mode = 2 # 1 for expProg, 2 for demo 1, 3 for demo 2, 4 for demo 3
if mode == 1:
    expProg = Process("ExpProg.exe")
    DoStuffAddress = 0x00401010
    argForm = ArgFormat().pushVal(4,"doStuff")
    fn = expProg.remoteFunction( DoStuffAddress,
                                 argForm)
    argsToFn = {'doStuff': 0}
    expProg.traceIntoCall( fn, argForm, argsToFn, "output.txt" )
    #fn(argsToFn)
    expProg.detach()
elif mode == 2:
    demo1 = Process("Demo 1.exe")
    # make the remote function
    fooAddress = 0x00401000
    fooForm = ArgFormat().pushVal(4,"stackArg").setReg("eax","argEax").setReg("ebx","argEbx")
    fooArgs = { 'stackArg': 0, 'argEax': 0, 'argEbx': 0 }
    fooFunc = demo1.remoteFunction( fooAddress,
                                    fooForm )
    # make and trace
    demo1.traceIntoCall( fooFunc, fooForm, fooArgs, "demo1Out.txt" )
    #demo1.traceIntoCall( None, ArgFormat(), {}, "demo1Out.txt", FooAddress )
    demo1.detach()
elif mode == 3:
    demo2 = Process("Demo 2.exe")
    CheckAnswerAddress = 0x00401070
    if 1:
        answer = demo2.derefInt(4211564, 4)
        i = 0
        while i < 100:
            print answer.read()
            time.sleep(1)
            i += 1
    else:
        demo2.traceIntoCall( None, ArgFormat(), {}, "demo2Out.txt", CheckAnswerAddress )
    
    demo2.detach()
elif mode == 4:
    # build list of processes with image name of haloce.exe
    procIds = Process.getRunningProcesses()
    halo_procs = [] # process objects
    for pid in procIds["haloce.exe"]: # create and attach to various haloce.exe processes
        halo_procs += [Process(None, pid)]

    # build lists of memory references to yaw and pitch [radians]
    orientationOffset = 0x402AD4B8
        # deref at 0 for 4 bytes for yaw    ( single )
        # deref at 4 for 4 bytes for pitch  ( single )
    yaw_mem_refs = []
    for halo_proc in halo_procs:
        yaw_mem_refs += [ halo_proc.derefInt( orientationOffset + 0 , 4 ) ]

    # modify time to modify the length of this loop
    totalTime = 25 # (in seconds)
    ticksPerSecond = 15
    totalTicks = totalTime * ticksPerSecond

    yaw_updated = False
    prev_yaw = 0
    host = None
    for i in xrange(0,totalTicks):
        yaw_updated = False
        for yaw_ref in yaw_mem_refs:
            curYaw = yaw_ref.read()
            if curYaw != prev_yaw:
                host = yaw_ref
                prev_yaw = curYaw
                yaw_updated = True
                break
        if yaw_updated:
            for yaw_ref in yaw_mem_refs:
                if yaw_ref != host:
                    yaw_ref.write( prev_yaw )
        time.sleep( 1.0 / ticksPerSecond )

    for halo_proc in halo_procs: # detach
        halo_proc.detach()
    
